/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.workflow.service.impl;

import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.workflow.domain.ActHiTaskinst;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.workflow.repository.ActHiTaskinstRepository;
import me.zhengjie.modules.workflow.service.ActHiTaskinstService;
import me.zhengjie.modules.workflow.service.dto.ActHiTaskinstDto;
import me.zhengjie.modules.workflow.service.dto.ActHiTaskinstQueryCriteria;
import me.zhengjie.modules.workflow.service.mapstruct.ActHiTaskinstMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wzp
* @date 2021-05-11
**/
@Service
@RequiredArgsConstructor
public class ActHiTaskinstServiceImpl implements ActHiTaskinstService {

    private final ActHiTaskinstRepository actHiTaskinstRepository;
    private final ActHiTaskinstMapper actHiTaskinstMapper;
    private final UserService userService;

    @Override
    public Map<String,Object> queryAll(ActHiTaskinstQueryCriteria criteria, Pageable pageable){
        Long currentUserId = SecurityUtils.getCurrentUserId();
        // 用户所在组(用户可以存在多个角色)
        List<String> assignee = new ArrayList<String>();
        // 放入当前用户
        assignee.add(String.valueOf(currentUserId));
        UserDto userDto = userService.findById(currentUserId);
        if(!userDto.getRoles().isEmpty()){
            for (RoleSmallDto role : userDto.getRoles()) {
                assignee.add(String.valueOf(role.getId()));
            }
        }
        // 已办任务 = 用户办理后的任务
        criteria.setAssignee(assignee);
        Page<ActHiTaskinst> page = actHiTaskinstRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(actHiTaskinstMapper::toDto));
    }

    @Override
    public List<ActHiTaskinstDto> queryAll(ActHiTaskinstQueryCriteria criteria){
        return actHiTaskinstMapper.toDto(actHiTaskinstRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ActHiTaskinstDto findById(String id) {
        ActHiTaskinst actHiTaskinst = actHiTaskinstRepository.findById(id).orElseGet(ActHiTaskinst::new);
        ValidationUtil.isNull(actHiTaskinst.getId(),"ActHiTaskinst","id",id);
        return actHiTaskinstMapper.toDto(actHiTaskinst);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActHiTaskinstDto create(ActHiTaskinst resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return actHiTaskinstMapper.toDto(actHiTaskinstRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ActHiTaskinst resources) {
        ActHiTaskinst actHiTaskinst = actHiTaskinstRepository.findById(resources.getId()).orElseGet(ActHiTaskinst::new);
        ValidationUtil.isNull( actHiTaskinst.getId(),"ActHiTaskinst","id",resources.getId());
        actHiTaskinst.copy(resources);
        actHiTaskinstRepository.save(actHiTaskinst);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            actHiTaskinstRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ActHiTaskinstDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ActHiTaskinstDto actHiTaskinst : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" procDefId",  actHiTaskinst.getProcDefId());
            map.put(" taskDefKey",  actHiTaskinst.getTaskDefKey());
            map.put(" procInstId",  actHiTaskinst.getProcInstId());
            map.put(" executionId",  actHiTaskinst.getExecutionId());
            map.put(" name",  actHiTaskinst.getName());
            map.put(" parentTaskId",  actHiTaskinst.getParentTaskId());
            map.put(" description",  actHiTaskinst.getDescription());
            map.put(" owner",  actHiTaskinst.getOwner());
            map.put(" assignee",  actHiTaskinst.getAssignee());
            map.put(" startTime",  actHiTaskinst.getStartTime());
            map.put(" claimTime",  actHiTaskinst.getClaimTime());
            map.put(" endTime",  actHiTaskinst.getEndTime());
            map.put(" duration",  actHiTaskinst.getDuration());
            map.put(" deleteReason",  actHiTaskinst.getDeleteReason());
            map.put(" priority",  actHiTaskinst.getPriority());
            map.put(" dueDate",  actHiTaskinst.getDueDate());
            map.put(" formKey",  actHiTaskinst.getFormKey());
            map.put(" category",  actHiTaskinst.getCategory());
            map.put(" tenantId",  actHiTaskinst.getTenantId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}